package com.zh.business.service.mp;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zh.zhbootcommon.utils.common.AESUtils;
import com.zh.business.config.forest.WeChatClent;
import com.zh.zhbootcommon.common.MiniConstants;
import com.zh.zhbootcommon.entity.mp.MiniUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 描述: 微信小程序用户信息
 *
 * @author: yanglin
 * @Date: 2021-08-17-14:26
 * @Version: 1.0
 */
@Slf4j
@Service
public class WechatService {

    @Autowired
    WeChatClent miniClent;

    /**
     * 根据code换取session_key和openid
     * {"session_key":"DAzo1lpSNGYVaWfrQ\/PSYg==","openid":"o-HI-43cf_WLMUvSOeyLv30caEtE"}
     *
     * @param jsCode
     * @return
     */
    public String getWechatSessionAndOpenId(String jsCode) {
        String jsonStr = "";
        try {
            jsonStr = miniClent.getJsCode2Session(MiniConstants.APP_ID, MiniConstants.APP_SECRET, jsCode);
            log.info("根据code换取session_key和openid->{}", jsonStr);
        } catch (Exception e) {
            log.error("getWechatSessionAndOpenId error -> ", e.getMessage());
        }
        return jsonStr;
    }

    /**
     * 解密微信密文获取用户数据
     * @param iv
     * @param encryptedData
     * @param sessionKey
     * @return
     */
    public MiniUserInfo mergeMiniUser(String iv, String encryptedData, String sessionKey){
        MiniUserInfo userInfo = new MiniUserInfo();
        JSONObject jsonObject = new JSONObject();
        String jsonStr = AESUtils.decryptUserInfo(encryptedData, sessionKey, iv);
        log.info("解密微信密文获取用户数据->{}", jsonStr);
        // {"openId":"o-HI-43cf_WLMUvSOeyLv30caEtE","nickName":"微信用户","gender":0,"language":"",
        // "city":"","province":"","country":"",
        // "avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
        // "watermark":{"timestamp":1629189486,"appid":"wx9b052a23bcf4d215"}}
        if (StrUtil.isNotBlank(jsonStr)) {
            jsonObject = JSONUtil.parseObj(jsonStr);
            userInfo.setOpenId(jsonObject.getStr("openId"));
            userInfo.setMName(jsonObject.getStr("nickName"));
            userInfo.setMImg(jsonObject.getStr("avatarUrl"));
            userInfo.setMSex(Integer.parseInt(jsonObject.getStr("gender")));
        }
        return userInfo;
    }


}
